package org.goodsence.framework.websocket;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author zty
 * @apiNote
 * @project_name the-revolt
 * @user tain
 * @create_at 2023/6/15 16:46
 * @create_vio IntelliJ IDEA
 */
public class DefaultWebSocketHandler extends TextWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String receivedMessage = message.getPayload();
        session.sendMessage(new TextMessage(receivedMessage));
    }

    /**
     * 建立连接后触发的回调
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        WebSocketUtils.getSessions().add(session);
        System.out.println("有新连接加入！当前在线人数为:{}" + WebSocketUtils.getSessions().size());
    }

    /**
     * 收到消息时触发的回调
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        System.out.println("收到新的消息！内容:{}" + message.getPayload().toString());
    }

    /**
     * 发生异常，关闭连接
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        WebSocketUtils.getSessions().remove(session);
        System.out.println("websocket发生异常！" + exception);
    }

    /**
     * 关闭连接
     * @param session
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        WebSocketUtils.getSessions().remove(session);
        System.out.println("webSocket关闭连接，状态：{}，当前连接数：{}" + closeStatus + WebSocketUtils.getSessions().size());
    }

    /**
     * 是否支持消息分片
     * @return
     */
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
